import { AppName } from '../../app.config.js';
import fs from 'fs';
import path from 'path';
import common from '../../../../lib/common/common.js';
const __dirname = path.resolve() + path.sep + 'plugins' + path.sep + AppName;
// 文件存放路径
export const __PATH = {
  //更新日志
  updata_log_path: path.join(__dirname, 'vertion.txt'),
  //用户数据
  player_path: path.join(__dirname, '/resources/data/mz_player'),
  //纳戒
  thing_path: path.join(__dirname, '/resources/data/mz_thing'),
  rensheng_path: path.join(__dirname, '/resources/data/mz_rensheng'),
};
/**
 * 判断对象是否不为undefined且不为null
 * @param obj 对象
 * @returns
  */
  export async function isNotNull(obj) {
    return obj !== undefined && obj !== null;
  }
//检查存档是否存在，存在返回true;
export async function existplayer(usr_qq) {
    let exist_player;
    exist_player = fs.existsSync(`${__PATH.player_path}/${usr_qq}.json`);
    if (exist_player) {
      return true;
    }
    return false;
  }
  export async function existrensheng(usr_qq) {
    let exist_player;
    exist_player = fs.existsSync(`${__PATH.rensheng_path}/${usr_qq}.json`);
    if (exist_player) {
      return true;
    }
    return false;
  }
  export async function Write_player(usr_qq, player) {
    let dir = path.join(__PATH.player_path, `${usr_qq}.json`);
    let new_ARR = JSON.stringify(player, '', '\t');
    fs.writeFileSync(dir, new_ARR, 'utf8', err => {
      console.log('写入成功', err);
    });
    return;
  }
  export async function Write_rensheng(usr_qq, rensheng) {
    let dir = path.join(__PATH.rensheng_path, `${usr_qq}.json`);
    let new_ARR = JSON.stringify(rensheng, '', '\t');
    fs.writeFileSync(dir, new_ARR, 'utf8', err => {
      console.log('写入成功', err);
    });
    return;
  }
  export async function Write_thing(usr_qq, thing) {
    let dir = path.join(__PATH.thing_path, `${usr_qq}.json`);
    let new_ARR = JSON.stringify(thing, '', '\t');
    fs.writeFileSync(dir, new_ARR, 'utf8', err => {
      console.log('写入成功', err);
    });
    return;
  }
  export async function Read_player(usr_qq) {
    let playerPath =`${__PATH.player_path}/${usr_qq}.json`
    //根据长度判读是否是分身
    let dir = path.join(playerPath);
    let player = fs.readFileSync(dir, 'utf8', (err, data) => {
      if (err) {
        console.log(err);
        return 'error';
      }
      return data;
    });
    //将字符串数据转变成数组格式
    player = JSON.parse(player);
    return player;
  }
  export async function Read_rensheng(usr_qq) {
    let playerPath =`${__PATH.rensheng_path}/${usr_qq}.json`
    //根据长度判读是否是分身
    let dir = path.join(playerPath);
    let player = fs.readFileSync(dir, 'utf8', (err, data) => {
      if (err) {
        console.log(err);
        return 'error';
      }
      return data;
    });
    //将字符串数据转变成数组格式
    player = JSON.parse(player);
    return player;
  }
  export async function synchronization(e) {
    if (!e.isMaster) {
      return;
    }
    e.reply('存档开始同步');
    let playerList = [];
    let files = fs
        .readdirSync('./plugins/' + AppName + '/resources/data/mz_player')
        .filter(file => file.endsWith('.json'));
    for (let file of files) {
      file = file.replace('.json', '');
      playerList.push(file);
    }
    for (let player_id of playerList) {
      let usr_qq = player_id;
      let player = await Read_player(usr_qq)
      let ziduan = [
        '称号',
      ];
  
      for (let k of ziduan) {
        if (!isNotNull(player[k])) {
          player[k] = "无";
        }
      }
    await Write_player(usr_qq, player);
    e.reply('存档同步结束');

    // NOTE: 魔术师同步，开发者专用，要使用请删除注释
    /*
      const thingType = ''; // 填写欲抹除物品类型
      const thingName = ''; // 填写欲抹除物品名称

      const objArr = await clearNajieThing(thingType, thingName);
      e.reply('物品自动抹除结束');

      const newThingType = '';
      const newThingName = ''; // 填写新物品
      const N = 1; // 填写

      objArr.map(uid_tnum => {
        const usrId = Object.entries(uid_tnum)[0][0];
        Add_najie_thing(usrId, newThingName, newThingType, uid_tnum.usrId * N);
      });
      e.reply('物品自动替换结束');
    */
    return;
    }
  }

  export async function getplayerdang(e,usr_qq) {
    if (!e.isGroup) {
      return;
    } 
    let ifexistplay = await existplayer(usr_qq);
    
    if (ifexistplay) {
      e.reply("已有存档");
      return;
    }
    
    let File_msg = fs.readdirSync(__PATH.player_path);
    let n = File_msg.length + 1;
    
    let new_player = {
      id: usr_qq,
      sex: 0, 
      名号: `路人甲${n}号`,
      宣言: '这个人很懒还没有写',
      称号: `无`,
      积分: 0,
      坤坤长度: 0,
      lastTriggerDate: "无"
    };
    
    await Write_player(usr_qq, new_player);
    
    let new_thing = {
      道具: [],
    };
    
    await Write_thing(usr_qq, new_thing);
    
    e.reply("创建存档成功");
  }
  
  
  
